<?php
require_once("inc.member.php");

$this_title="$vars[member_title] &raquo; ".__("Support");
$page_title=__("Support");

if($_GET['action']=='new')
	$content_title=__("Compose");
elseif($_GET['action']=='inbox')
	$content_title=__("Inbox");
elseif($_GET['action']=='outbox')
	$content_title=__("Outbox");
else
	$content_title=__("Support");

$item_per_page=$vars['user_item_per_page'];
$td_width=100;

//tab
$css="<link rel='stylesheet' type='text/css' href='".CSS_URL."/tab/tab".(USER_BROWSER=='msie'? "-ie" : "").".css' />\n";
$tab=
"<ul class='tabs-nav' id='_tab'>
  <li class='tabs-".($_GET['action']=='inbox' || !$_GET['action']? "" : "un")."selected' rel='inbox'><a href='".$vars['file']['member']['support']."?action=inbox'><span>".__("Inbox")."</span></a></li>
  <li class='tabs-".($_GET['action']=='new'? "" : "un")."selected' rel='new'><a href='".$vars['file']['member']['support']."?action=new'><span>".__("Compose")."</span></a></li>
  <li class='tabs-".($_GET['action']=='outbox'? "" : "un")."selected' rel='outbox'><a href='".$vars['file']['member']['support']."?action=outbox'><span>".__("Outbox")."</span></a></li>
</ul>
<div class='tabs-panel' style='width:97%;'><%tab_content%></div>";

//#####AJAX CALL#####
if($_GET["aj"] && $_GET["check_uid"]){
	$ajresult = ajax_check_user($post_d['uid']);
	if($ajresult['status'] == 3){
		$ajmsg = "The Member ID '$post_s[uid]' could not be found.";
	}elseif($ajresult['status'] == 2){
		$ajmsg = "The Member ID '$post_s[uid]' could not be found.";
	}elseif($ajresult['status'] == 1){
		$ajmsg = "Member ID '$post_s[uid]', name: {$ajresult['user_detail']['name']}";
	}
	$status = $ajresult['status'];

	print format_xml(array('status'=>$status, 'msg'=>$ajmsg));
	exit;
}
//#####END AJAX CALL#####

if($_GET['action']=="new"){
 //#####POST#####
 if($_POST['__req']){
  $errmsg=verify_form_data("messaging", $post_s);
  if(!$errmsg){
   if(!$post_s['to_type']){
    $errmsg=__("Please select the recipient.")."<br />\n";
   }if($post_s['to_type']=="u"){
    if(!$recipient=get_user_detail_by_id($post_s['to_uid'])){
     $errmsg=replace_tag(__("The member ID '<%uid%>' could not be found."), array("<%uid%>"=>$post_h['to_uid']))."<br />\n";
    }
    if($post_s['to_uid']==$uid){
     $errmsg.=__("You cannot send message to yourself.")."<br />\n";
    }
   }
  }
  if(!$errmsg){
   $datetime=ndate("");
   $sql="insert into $db->messaging (from_type, from_uid, from_deleted, to_type, to_uid, to_read, to_deleted, subject, message, cdate) values ('u', '$uid', 'n', '$post_d[to_type]', '$post_d[to_uid]', 'n', 'n', '$post_d[_subject]', '$post_d[_message]', '$datetime')";
   if(mysql_query($sql)){
    $msg.=__("Your message has been successfully sent.")."<br />\n";
    send_recipient($r_user['name'], $r_user['email'], $post_s['to_type'], $recipient['name'], $recipient['email']);
   }else{
    $errmsg.=__("There is some error and your message could not be sent. Please try again later.")."<br />\n";
   }
  }

  $msg=$msg? format_msg($msg) : "";
  $errmsg=$errmsg? format_err(__("There is some error(s), please correct them before continuing:")."<br />\n<br />\n$errmsg") : "";
 }
 //#####END POST#####

 $form_fields=array("to_type"=>"a","to_uid"=>"","_subject"=>"","_message"=>"");
 foreach($form_fields as $field => $default){
  $db_fieldname=preg_match('/^_/', $field)? substr($field, 1) : $field;
  $dis[$field]=!$post_s["__req"]? $default : $post_h[$field];
 }
/*
 $recipient_row="
 <tr>
  <td>".__("Recipient").__(":").__("*")."</td>
  <td><input type='radio' name='to_type' value='a' ".($dis['to_type']=='a'? "checked='checked'" : "")." id='tt_admin'> <label for='tt_admin'>".__("Management Staff")."</label><br />\n
      <input type='radio' name='to_type' value='u' ".($dis['to_type']=='u'? "checked='checked'" : "")." id='tt_user'> <label for='tt_user'>".__("Member")."</label> <input type='text' name='to_uid' class='inputbox' style=\"width:187px;\" value=\"$dis[to_uid]\" /> <input type='button' id='check_uid_btn' value=\"".__("Load Member")."\" /> <div id='member_detail'></div>
  </td>
 </tr>";*/  
 
 $messaging=$msg.$errmsg.
'
<div class="panel panel-primary">
	<form class="form-horizontal" name="new_form" method="post" action="'.$this_file.'?action=new">
	<input type="hidden" name="__req" value="1" />
	<input type="hidden" name="support" value="new" />
	<input type="hidden" name="action" value="new" />
	<div class="panel-heading">
		<h4>'.$content_title.'</h4>				          
	</div>
	<div class="panel-body">
		<div class="form-group">
			<label for="disabledinput" class="col-sm-3 control-label">'.__('Recipient').'</label>
			<div class="col-sm-6">
				'."<input type='radio' name='to_type' value='a' ".($dis['to_type']=='a'? "checked='checked'" : "")." id='tt_admin'>".__("Management Staff").'
			</div>
		</div>
		<div class="form-group">
			<label for="disabledinput" class="col-sm-3 control-label">'.__('Subject').'</label>
			<div class="col-sm-6">
				<input type="text" class="form-control" id="_subject" name="_subject" value="'.$dis['_subject'].'">
			</div>
		</div>
		<div class="form-group">
			<label for="disabledinput" class="col-sm-3 control-label">'.__('Message').'</label>
			<div class="col-sm-6">
				<textarea name="_message" id="_message" cols="50" rows="15" class="form-control">'.$dis['_message'].'</textarea>
			</div>
		</div>
	</div>
	<div class="panel-footer">
		<div class="row">
			<div class="col-sm-6 col-sm-offset-3">
				<div class="btn-toolbar">
					<input type="submit" name="submit_btn" value="'.__("Send").'"/>
				</div>
			</div>
		</div>
	</div>
	</form>
</div>
';

//#################INBOX
}elseif($_GET['action']=="inbox" || !$_GET['action']){
 //back button
 $url_referer=$_SERVER["HTTP_REFERER"];
 if($post_s["back_url"]){
  $back_url=$post_s["back_url"];
 }elseif($url_referer && !strstr($url_referer, $this_file)){
  $back_url=$url_referer;
 }else{
  $back_url=$vars['file']['member']['support']."?action=inbox";
 }

 //#####VIEW A MESSAGE#####
 if($_GET['view']){
  if(!$_GET['mid'] || !is_numeric($_GET['mid']) || $_GET['mid'] <= 0){
   $errmsg=__("Invalid message.")."<br />\n";
  }elseif(!@mysql_num_rows($r=mysql_query("select * from $db->messaging where id='$get_d[mid]' and to_type='u' and to_uid='$uid'"))){
   $errmsg=__("Invalid message.")."<br />\n";
  }

  if($errmsg){
   $messaging=format_err($errmsg);
  }else{
   $message=mysql_fetch_assoc($r);

   //update message to read, if not already
   if($message['to_read']!='y'){
    if(!mysql_query($sql="update $db->messaging set to_read='y' where id='$message[id]' limit 1")){
     $critical_error.="Error updating the message ID: $message[id] to 'read' status.<br />\n<br />\nSQL: $sql<br />\n<br />\nError: ".mysql_error()."<br />\n";
    }
   }

   //#####REPLY POST#####
   if($_POST['__req']){
    $errmsg=verify_form_data("messaging", $post_s);

    if(!$errmsg){
     $datetime=ndate();
     $subject=(substr($message['subject'], 0, 3)!='RE:'? 'RE: ' : '').AddSlashes($message['subject']);
     $sql="insert into $db->messaging (from_type, from_uid, from_deleted, to_type, to_uid, to_read, to_deleted, subject, message, cdate) values ('u', '$uid', 'n', '".mysql_real_escape_string($message['from_type'])."', '".mysql_real_escape_string($message['from_uid'])."', 'n', 'n', '$subject', '$post_d[_message]', '$datetime')";
     if(mysql_query($sql)){
      $msg=__("Your message has been successfully sent.")."<br />\n";
      $sender=get_user_detail_by_id($message['from_uid']);
      send_recipient($r_user['name'], $r_user['email'], $message['from_type'], $sender['name'], $sender['email']);
     }else{
      $errmsg=__("There is some error and your message could not be sent. Please try again later.")."<br />\n";
     }
    }

    $msg=$msg? format_msg($msg) : "";
    $errmsg=$errmsg? format_err(__("There is some error(s), please correct them before continuing:")."<br />\n<br />\n$errmsg") : "";
   }
   //#####END REPLY POST#####

   $form_fields=array("_message"=>"");
   foreach($form_fields as $field => $default){
    $db_fieldname=preg_match('/^_/', $field)? substr($field, 1) : $field;
    $dis[$field]=!$post_s["__req"]? $default : $post_h[$field];
   }

   if($message['from_type']=='u'){
    $sender=get_user_detail_by_id($message['from_uid']);
    $sender="$sender[name] (UID #$sender[id])";
   }else{
    $sender=__("Management");
   }
   $inbox=$errmsg.$msg.
'
<div class="panel panel-primary">
	<form class="form-horizontal" name="reply_form" method="post" action="'.$this_file.'?action=inbox&view=1&mid='.$message['id'].'">
	<input type="hidden" name="__req" value="1" />
	<input type="hidden" name="back_url" value="'.$back_url.'" />
	<div class="panel-heading">
		<h4>'.$content_title.'</h4>				          
	</div>
	<div class="panel-body">
		<div class="form-group">
			<label for="disabledinput" class="col-sm-3 control-label">'.__('Subject').'</label>
			<div class="col-sm-6">
				'.$message['subject'].'
			</div>
		</div>
		<div class="form-group">
			<label for="disabledinput" class="col-sm-3 control-label">'.__('Sender').'</label>
			<div class="col-sm-6">
				'.$sender.'
			</div>
		</div>
		<div class="form-group">
			<label for="disabledinput" class="col-sm-3 control-label">'.__('Received').'</label>
			<div class="col-sm-6">
				'.date($vars['date_format'], strtotime($message['cdate'])).'
			</div>
		</div>
		<div class="form-group">
			<label for="disabledinput" class="col-sm-3 control-label">'.__('Message').'</label>
			<div class="col-sm-6">
				'.nl2br($message['message']).'
			</div>
		</div>
		<div class="form-group">
			<label for="disabledinput" class="col-sm-3 control-label">'.__('Add Reply').'</label>
			<div class="col-sm-6">
				<textarea name="_message" id="_message" cols="50" rows="15" class="form-control">'.$dis['_message'].'</textarea>
			</div>
		</div>
	</div>
	<div class="panel-footer">
		<div class="row">
			<div class="col-sm-6 col-sm-offset-3">
				<div class="btn-toolbar">
					<input type="button" value="'.__("Back").'" onclick="location=\''.$back_url.'\';">
					<input type="submit" name="submit_btn" value="'.__("Send").'"/>
				</div>
			</div>
		</div>
	</div>
	</form>
</div>
'; 

   $messaging=$inbox;
  }
 }
 //#####END VIEW A MESSAGE#####

 //#####DELETE MESSAGE POST#####
 if($_POST['__req'] && $_POST['delete']){
  foreach($post_s as $f=>$v){
   if($v && preg_match('/^mid[0-9]+$/', $f)){
    $mid.=($mid? "," : "").preg_replace('/^mid/', '', $f);
    $dis[$f]=$v;
   }
  }

  if(!$mid){
   $errmsg.=__("Please select a message to delete.")."<br />\n";
  }else{
   $sql="update $db->messaging set to_deleted='y' where id in ($mid)";
   if(mysql_query($sql)){
    $msg=__("The selected message(s) has been successfully deleted.")."<br />\n";
   }else{
    $errmsg.=__("There is some error and your message could not be deleted. Please try again later.")."<br />\n";
   }
  }

  $msg=$msg? format_msg($msg) : "";
  $errmsg=$errmsg? format_err(__("There is some error(s), please correct them before continuing:")."<br />\n<br />\n$errmsg") : "";
 }
 //#####END DELETE MESSAGE POST#####

 //#####LIST ALL MESSAGES#####
 if(!$_GET['view']){
  $count_sql="select count(*) from $db->messaging where to_type='u' and to_uid='$uid' and to_deleted='n'";
  $record_sql="select * from $db->messaging where to_type='u' and to_uid='$uid' and to_deleted='n' order by cdate desc limit <%limit_start%>, <%limit%>";

  $cur_page=$_GET["nav"];
  $total_record=@mysql_result(mysql_query($count_sql), 0);
  $total_page=ceil($total_record/$item_per_page);
  $page=($cur_page? ($cur_page>$total_page? $total_page : ($cur_page<1? 1 : $cur_page)) : 1);
  $limit_start=($page-1)*$item_per_page;
  $nav_link=format_page($page, $total_page, 15);
  $this_page_total=@mysql_num_rows($r=mysql_query(str_replace("<%limit_start%>", $limit_start, str_replace("<%limit%>", $item_per_page, $record_sql))));
  $total_unread=0;
  $k=0;
  for($i=0;$i<$this_page_total;$i++){
   $message=mysql_fetch_assoc($r);
   if($message['from_type']=='u' && !$users[$message["from_uid"]]){
    $users[$message["from_uid"]]=get_user_detail_by_id($message['from_uid']);
   }
   if($message['to_read']=='n'){
    $total_unread++;
   }
   $message_row1.="
   <div class='inbox_row".($message['to_read']=='n'? " inbox_unread" : "")."'>
    <div class='inbox_chk'><input type='checkbox' name='mid$message[id]'".($dis['mid'.$message['id']]? " checked='checked'" : "")." /></div>
    <div class='inbox_sender'><a href='$this_file?action=inbox&view=1&mid=$message[id]'>".($message['from_type']=='u'? $users[$message['from_uid']]['name'] : __("Management"))."</a></div>
    <div class='inbox_subject'><a href='$this_file?action=inbox&view=1&mid=$message[id]'>$message[subject]</a></div>
    <div class='inbox_date'><a href='$this_file?action=inbox&view=1&mid=$message[id]'>".(strtotime($message['cdate'])>=mktime(0,0,0,ndate('n'),ndate('j'),ndate('Y'))? date($vars['inbox_date_format_today'], strtotime($message['cdate'])) : date($vars['inbox_date_format'], strtotime($message['cdate'])))."</a></div><div class='clear'></div>
   </div>";
   
   if($message['to_read']=='n'){
		$message_row.='
		   	<tr class="'.($k==0?'even':'odd').'">
				<td>'."<input type='checkbox' name='mid$message[id]'".($dis['mid'.$message['id']]? " checked='checked'" : "")." />".'</td>
				<td>'."<a href='".$this_file."?action=inbox&view=1&mid=".$message['id']."'>".($message['from_type']=='u'? $users[$message['from_uid']]['name'] : __("Management")).'</td>
				<td>'."<a href='".$this_file."?action=inbox&view=1&mid=".$message['id']."'>$message[subject]</a>".'</td>
		        <td class="center">'."<a href='".$this_file."?action=inbox&view=1&mid=".$message['id']."'>".(strtotime($message['cdate'])>=mktime(0,0,0,ndate('n'),ndate('j'),ndate('Y'))? date($vars['inbox_date_format_today'], strtotime($message['cdate'])) : date($vars['inbox_date_format'], strtotime($message['cdate']))).'</a></td>
			</tr>		
		';
   }else{
		$message_row.='
		   	<tr class="'.($k==0?'even':'odd').'">
				<td>'."<input type='checkbox' name='mid$message[id]'".($dis['mid'.$message['id']]? " checked='checked'" : "")." />".'</td>
				<td>'."<a href='".$this_file."?action=inbox&view=1&mid=".$message['id']."'>".($message['from_type']=='u'? $users[$message['from_uid']]['name'] : __("Management")).'</td>
				<td>'."<a href='".$this_file."?action=inbox&view=1&mid=".$message['id']."'>$message[subject]</a>".'</td>
		        <td class="center">'."<a href='".$this_file."?action=inbox&view=1&mid=".$message['id']."'>".(strtotime($message['cdate'])>=mktime(0,0,0,ndate('n'),ndate('j'),ndate('Y'))? date($vars['inbox_date_format_today'], strtotime($message['cdate'])) : date($vars['inbox_date_format'], strtotime($message['cdate']))).'</a></td>
			</tr>	
	   ';
   }
   $k=1-$k;
  }
  $message_list=$msg.$errmsg.
  '
<div class="panel panel-sky">
	<form class="form-horizontal" name="delete_inbox_form" method="post" action="'.$this_file.'?action=inbox">
  	<input type="hidden" name="__req" value="1" />
  	<input type="hidden" name="delete" value="1" />
  	<input type="hidden" name="back_url" value="'.$back_url.'" />
	<div class="panel-heading">
		<h4>'.$content_title.'</h4>
		<div class="options">   
			<a href="javascript:;"><i class="fa fa-cog"></i></a>
			<a href="javascript:;"><i class="fa fa-wrench"></i></a>
			<a href="javascript:;" class="panel-collapse"><i class="fa fa-chevron-down"></i></a>
	    </div>
    </div>
    <div class="panel-body collapse in">
		<table cellpadding="0" cellspacing="0" border="0" class="table table-striped table-bordered datatables" id="example">
		<thead>
			<tr>
				<th></th>
				<th>'.__("Sender#").'</th>
				<th>'.__("Subject").'</th>
				<th>'.__("Received").'</th>
			</tr>
		</thead>
		<tbody>
			'.$message_row.'
		</tbody>
		</table>
	</div>
</div>
';
  
  $messaging=$message_list;
 }
 //#####END LIST ALL MESSAGES#####
//#################OUTBOX
}elseif($_GET['action']=="outbox"){
 //back button
 $url_referer=$_SERVER["HTTP_REFERER"];
 if($post_s["back_url"]){
  $back_url=$post_s["back_url"];
 }elseif($url_referer && !strstr($url_referer, $this_file)){
  $back_url=$url_referer;
 }else{
  $back_url=$vars['file']['member']['support']."?action=outbox";
 }

 //#####VIEW A MESSAGE#####
 if($_GET['view']){
  if(!$_GET['mid'] || !is_numeric($_GET['mid']) || $_GET['mid'] <= 0){
   $errmsg=__("Invalid message.")."<br />\n";
  }elseif(!@mysql_num_rows($r=mysql_query("select * from $db->messaging where id='$get_d[mid]' and from_type='u' and from_uid='$uid'"))){
   $errmsg=__("Invalid message.")."<br />\n";
  }

  if($errmsg){
   $messaging=format_err($errmsg);
  }else{
   $message=mysql_fetch_assoc($r);

   if($message['to_type']=='u'){
    $recipient=get_user_detail_by_id($message['to_uid']);
    $recipient="$recipient[name] (UID #$recipient[id])";
   }else{
    $recipient=__("Management");
   }
   $outbox=$errmsg.$msg.
'
<div class="panel panel-primary">
	<form class="form-horizontal" method="post" action="'.$this_file.'">
	<input type="hidden" name="back_url" value="'.$back_url.'" />
	<div class="panel-heading">
		<h4>'.$content_title.'</h4>				          
	</div>
	<div class="panel-body">
		<form class="form-horizontal">
			<dl class="dl-horizontal">
            	<dt>'.__("Subject").__(":").'</dt>
                <dd>'.$message['subject'].'</dd>
                <dt>'.__("Subject").__(":").'</dt>
                <dd>'.$recipient.'</dd>
                <dt>'.__("Sent").__(":").'</dt>
                <dd>'.date($vars['date_format'], strtotime($message['cdate'])).'</dd>
                <dt>'.__("Message").__(":").'</dt>
                <dd>'.nl2br($message['message']).'</dd>
             </dl>
		</form>
	</div>
	<div class="panel-footer">
		<div class="row">
			<div class="col-sm-6 col-sm-offset-3">
				<div class="btn-toolbar">
					<input type="button" value="'.__("Back").'" onclick="location=\''.$back_url.'\';">
				</div>
			</div>
		</div>
	</div>
	</form>
</div>
';    
 
   $messaging=$outbox;
  }
 }
 //#####END VIEW A MESSAGE#####

 //#####DELETE MESSAGE POST#####
 if($_POST['__req'] && $_POST['delete']){
  foreach($post_s as $f=>$v){
   if($v && preg_match('/^mid[0-9]+$/', $f)){
    $mid.=($mid? "," : "").preg_replace('/^mid/', '', $f);
    $dis[$f]=$v;
   }
  }

  if(!$mid){
   $errmsg.=__("Please select a message to delete.")."<br />\n";
  }else{
   $sql="update $db->messaging set from_deleted='y' where id in ($mid)";
   if(mysql_query($sql)){
    $msg=__("The selected message(s) has been successfully deleted.")."<br />\n";
   }else{
    $errmsg.=__("There is some error and your message could not be deleted. Please try again later.")."<br />\n";
   }
  }

  $msg=$msg? format_msg($msg) : "";
  $errmsg=$errmsg? format_err(__("There is some error(s), please correct them before continuing:")."<br />\n<br />\n$errmsg") : "";
 }
 //#####END DELETE MESSAGE POST#####

 if(!$_GET['view']){
  $count_sql="select count(*) from $db->messaging where from_type='u' and from_uid='$uid' and from_deleted='n'";
  $record_sql="select * from $db->messaging where from_type='u' and from_uid='$uid' and from_deleted='n' order by cdate desc limit <%limit_start%>, <%limit%>";
  
  $cur_page=$_GET["nav"];
  $total_record=@mysql_result(mysql_query($count_sql), 0);
  $total_page=ceil($total_record/$item_per_page);
  $page=($cur_page? ($cur_page>$total_page? $total_page : ($cur_page<1? 1 : $cur_page)) : 1);
  $limit_start=($page-1)*$item_per_page;
  $nav_link=format_page($page, $total_page, 15);
  $this_page_total=@mysql_num_rows($r=mysql_query(str_replace("<%limit_start%>", $limit_start, str_replace("<%limit%>", $item_per_page, $record_sql))));
  $total_unread=0;
  $k=0;
  for($i=0;$i<$this_page_total;$i++){
   $message=mysql_fetch_assoc($r);
   if($message['to_type']=='u' && !$users[$message["to_uid"]]){
    $users[$message["to_uid"]]=get_user_detail_by_id($message['to_uid']);
   }
   $message_row1.="
   <div class='outbox_row'>
    <div class='outbox_chk'><input type='checkbox' name='mid$message[id]'".($dis['mid'.$message['id']]? " checked='checked'" : "")." /></div>
    <div class='outbox_recipient'><a href='$this_file?action=outbox&view=1&mid=$message[id]'>".($message['to_type']=='u'? $users[$message['to_uid']]['name'] : __("Management"))."</a></div>
    <div class='outbox_subject'><a href='$this_file?action=outbox&view=1&mid=$message[id]'>$message[subject]</a></div>
    <div class='outbox_date'><a href='$this_file?action=outbox&view=1&mid=$message[id]'>".(strtotime($message['cdate'])>=mktime(0,0,0,ndate('n'),ndate('j'),ndate('Y'))? date($vars['inbox_date_format_today'], strtotime($message['cdate'])) : date($vars['inbox_date_format'], strtotime($message['cdate'])))."</a></div><div class='clear'></div>
   </div>";
      
   if($message['to_read']=='n'){
		$message_row.='
		   	<tr class="'.($k==0?'even':'odd').'">
				<td>'."<input type='checkbox' name='mid$message[id]'".($dis['mid'.$message['id']]? " checked='checked'" : "")." />".'</td>
				<td>'."<a href='".$this_file."?action=outbox&view=1&mid=".$message['id']."'>".($message['to_type']=='u'? $users[$message['to_uid']]['name'] : __("Management")).'</td>
				<td>'."<a href='".$this_file."?action=outbox&view=1&mid=".$message['id']."'>$message[subject]</a>".'</td>
		        <td class="center">'."<a href='".$this_file."?action=outbox&view=1&mid=".$message['id']."'>".(strtotime($message['cdate'])>=mktime(0,0,0,ndate('n'),ndate('j'),ndate('Y'))? date($vars['inbox_date_format_today'], strtotime($message['cdate'])) : date($vars['inbox_date_format'], strtotime($message['cdate']))).'</a></td>
			</tr>		
		';
   }else{
		$message_row.='
		   	<tr class="'.($k==0?'even':'odd').'">
				<td>'."<input type='checkbox' name='mid$message[id]'".($dis['mid'.$message['id']]? " checked='checked'" : "")." />".'</td>
				<td>'."<a href='".$this_file."?action=outbox&view=1&mid=".$message['id']."'>".($message['to_type']=='u'? $users[$message['to_uid']]['name'] : __("Management")).'</td>
				<td>'."<a href='".$this_file."?action=outbox&view=1&mid=".$message['id']."'>$message[subject]</a>".'</td>
		        <td class="center">'."<a href='".$this_file."?action=outbox&view=1&mid=".$message['id']."'>".(strtotime($message['cdate'])>=mktime(0,0,0,ndate('n'),ndate('j'),ndate('Y'))? date($vars['inbox_date_format_today'], strtotime($message['cdate'])) : date($vars['inbox_date_format'], strtotime($message['cdate']))).'</a></td>
			</tr>	
	   ';
   }
   $k=1-$k;
  }
  $message_list=$msg.$errmsg.
  '
<div class="panel panel-sky">
	<form class="form-horizontal" name="delete_outbox_form" method="post" action="'.$this_file.'?action=outbox">
  	<input type="hidden" name="__req" value="1" />
  	<input type="hidden" name="delete" value="1" />
  	<input type="hidden" name="back_url" value="'.$back_url.'" />
	<div class="panel-heading">
		<h4>'.$content_title.'</h4>
		<div class="options">   
			<a href="javascript:;"><i class="fa fa-cog"></i></a>
			<a href="javascript:;"><i class="fa fa-wrench"></i></a>
			<a href="javascript:;" class="panel-collapse"><i class="fa fa-chevron-down"></i></a>
	    </div>
    </div>
    <div class="panel-body collapse in">
		<table cellpadding="0" cellspacing="0" border="0" class="table table-striped table-bordered datatables" id="example">
		<thead>
			<tr>
				<th></th>
				<th>'.__("Recipient").'</th>
				<th>'.__("Subject").'</th>
				<th>'.__("Sent").'</th>
			</tr>
		</thead>
		<tbody>
			'.$message_row.'
		</tbody>
		</table>
	</div>
	<div class="panel-footer">
		<div class="row">
			<div class="col-sm-6 col-sm-offset-3">
				<div class="btn-toolbar">
					<input type="submit" name="submit_btn" value="'.__("Delete").'" />
				</div>
			</div>
		</div>
	</div>
	</form>
</div>
';

  $messaging=$message_list;
 }
}
//end process support

//javascript
$jvscript=
"<script type='text/javascript' src='".JS_URL."/get_file_gzip.php?file=".urlencode("jquery.js")."'></script>
<script type='text/javascript'>
jQuery(document).ready(function(j){
 j('form[@name=delete_inbox_form],form[@name=delete_outbox_form]').submit(function(){
  if(!confirm('".AddSlashes("Delete the selected message(s). Are you sure?")."')){
   return false;
  }
 });

 j('input[@name=to_uid]').click(function(){
  j('input[@name=to_type]:last').attr('checked','checked');
 });

 j('input#check_uid_btn').click(function(){
  j('div#member_detail').html('').removeClass('red');
  if(j('input[@name=to_uid]').val()==''){
   j('div#member_detail').html('".AddSlashes(__("Please provide a Member ID!"))."').addClass('red');
  }else{
   j(this).attr('disabled','disabled');
   j.ajax({
    url: '$this_file?aj=1&check_uid=1',
    data: {'uid': j('input[@name=to_uid]').val()},
    type: 'post',
    dataType: 'xml',
    error: function(){
     j('div#member_detail').html('".AddSlashes(__("Error checking..."))."').addClass('red');
    },
    success: function(data){
     var mesg='';
     if(j('loggedout', data).text()=='loggedout'){
      mesg='".AddSlashes(__("You have been logged out."))."';
     }else{
      j(data).find('msg').each(function(){
       mesg+=j(this).text()+' ';
      });
     }
     var status=j(data).find('status').text();
     j('div#member_detail').html(mesg).addClass(status==1? 'bold' : 'red');
    },
    complete: function(){
     j('input#check_uid_btn').attr('disabled','');
    }
   });
  }
 });
});
</script>";

$content=$messaging;

print format_member_page($content, $this_title, $content_title, $css.$jvscript);

function send_recipient($from_name, $from_email, $to_type, $to_name, $to_email){
 global $vars;
 if($to_type=="u"){
  $recipient=$to_name;
  $u_sub="$vars[title] - You Have a New Message";
  $u_msg="
  <p>Dear $recipient,</p>
  <p>You have a new message in your $vars[title] account. Please login to $vars[title] to check your message.</p>";
  email_user($to_email, $u_sub, $u_msg);
 }else{
  $recipient="Admin";
  $a_sub="$vars[title] - A New Message from Member";
  $a_msg="
  <p>Dear $recipient,</p>
  <p>A new message has been received from member. Please login to $vars[title] Administrative Panel to check the message.</p>";
  email_admin($a_sub, $a_msg, 'c');
 }
}
?>